package com.bruce.storage.controller;

import com.aliyuncs.utils.StringUtils;
import com.bruce.storage.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    @PostMapping("uploadFile")
    public void uploadFile(@RequestParam String bucketName,@RequestParam String contentId, @RequestPart MultipartFile file) {
        storageService.uploadFile(bucketName, contentId, file.getOriginalFilename(),"-1", file);
    }

    @GetMapping("downloadFile")
    public void downloadFile(@RequestParam String bucketName,@RequestParam String contentId, HttpServletResponse response) {
        InputStream inputStream = storageService.downloadFile(bucketName, contentId);
        String fileName = (String) storageService.getMetadata(bucketName, contentId).get("name");
        if(StringUtils.isEmpty(fileName)){
            fileName = contentId;
        }
        try(OutputStream outputStream = response.getOutputStream();) {
            response.setContentType("application/octet-stream");
            //解决跨域
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @GetMapping("metadata")
    public Map<String, ?> testGetMetadata(@RequestParam String bucketName,@RequestParam String contentId) {
        Map<String, ?> metadata = storageService.getMetadata(bucketName, contentId);
        return metadata;
    }

    @DeleteMapping("deleteFiles")
    public void deleteFiles(@RequestParam String bucketName,@RequestBody List<String> contentId) {
        storageService.deleteFiles(bucketName, contentId);

    }

    @DeleteMapping("deleteFile")
    public void deleteFile(@RequestParam String bucketName,@RequestParam String contentId) {
        storageService.deleteFile(bucketName, contentId);

    }


}
